package util.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;

import java.io.IOException;

/**
 * @author Gregory Boissinot
 */
public class JacksonWriter {

    public void writeMandatoryFieldValue(JsonGenerator jsonGenerator, String fieldName, Object fieldValue) throws IOException {
        writeFieldValue(jsonGenerator, fieldName, fieldValue, true);
    }

    public void writeOptionalFieldValue(JsonGenerator jsonGenerator, String fieldName, Object fieldValue) throws IOException {
        writeFieldValue(jsonGenerator, fieldName, fieldValue, false);
    }

    private void writeFieldValue(JsonGenerator jsonGenerator,
                                 String fieldName,
                                 Object fieldValue,
                                 boolean mandatoryField) throws IOException {

        boolean writeFieldValue = (fieldValue != null) || mandatoryField;
        if (writeFieldValue) {
            if (fieldValue instanceof String) {
                jsonGenerator.writeStringField(fieldName, (String) fieldValue);
                return;
            }
            jsonGenerator.writeObjectField(fieldName, fieldValue);
        }
    }
}
